/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package onpu_dms_xls.kernel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import onpu_dms_xls.exceptions.*;
import onpu_dms_xls.kernel.common.*;
import onpu_dms_xls.kernel.common.inputParameters.*;
import onpu_dms_xls.kernel.common.logAndDebug.LoggingFacade;

/**
 *
 * @author snbm
 */
public abstract class File_From_DB {

    protected File res;
    protected File templateXLS;
    protected File templateXML;
    protected FromDB_InputParameters input;
    protected VariableDeclaration[] varDeclArray;
    protected Connection conn;
    protected String TEMPORARY_XLS_FILE_NAME = "temporary_Name";
    protected String tempFolder;

    public File_From_DB(String inputXML, Connection con) throws MyException {
        tempFolder = Util.getTempFolderFromInputXML(inputXML);

        LoggingFacade.trace.info("Temporary folder name, read from input xml=" + tempFolder);

        LoggingFacade.trace.debug("____________________________");
        LoggingFacade.trace.debug("XLS_From_DB Input XML:");
        LoggingFacade.trace.debug(inputXML);
        LoggingFacade.trace.debug("____________________________");

        try {
            input = new FromDB_InputParameters(inputXML, tempFolder);
        } catch (IOException e) {
            throw new MyException("make_XLS_File_From_DB", "FromDB_InputParameters input = new FromDB_InputParameters(xml);", e.getMessage());
        }

        LoggingFacade.trace.trace("ALL INPUT PARAMETERS:");
        LoggingFacade.trace.trace(input.toString());

        //DB
        conn = con;
    }

    public static File_From_DB get_PDF_File_From_DB_Processor(String inputXML, Connection con) throws MyException {
        return new File_From_DB_PDF(inputXML, con);
    }

    public static File_From_DB get_XLS_File_From_DB_Processor(String inputXML, Connection con) throws MyException {
        return new File_From_DB_XLS(inputXML, con);
    }

    public File get_File_From_DB() throws MyException, SQLException {
        try {
            TemplatesLoader tl = TemplatesLoader.getTemplatesLoader(TemplatesLoader.TemplatesLoaders.DB);

            templateXML = tl.getTemplateFile(input.getConstantParam_temporaryFolder(), input.getDocumentClassId(), conn, TemplatesLoader.TemplatesLoaderFiles.XML_FILE);
            LoggingFacade.trace.info("created (temporary) template xml file:" + templateXML.getAbsolutePath());
            LoggingFacade.trace.debug("parsing... template XML" + templateXML.getAbsolutePath());
            try {
                varDeclArray = Util.generateVariablesDeclarationsArrayFromXMLFile(templateXML);
            } catch (FileNotFoundException e) {
                throw new MyXMLException("XLS_From_DB", "make_XLS_File_From_DB/1 section", "calling to Common.generateVariablesDeclarationsArrayFromXMLFile(templateXML)", e.getMessage());
            } catch (Exception e) {
                throw new MyException("XLS_From_DB", "make_XLS_File_From_DB/Util.generateVariablesDeclarationsArrayFromXMLFile(templateXML);", e.toString() + e.getMessage());
            }

//            LoggingFacade.trace.info("-------------- read these variablesDeclarations From XML template:");
//            for (VariableDeclaration vd : varDeclArray) {
//                LoggingFacade.trace.info("\t" + vd.toString());
//            }

            // майже костиль - якщо є значення в змінної
            //singleFromDBQuery, то це значення записується в всі
            //поля singleFromDBQuery ітераційних змінних
            fillSingleFromDBQueryFromInputIfExists(varDeclArray, input.getConstantParam_singleFromDBQuery());

            fillOtherVarsInVarDeclArrWithValuesFromInput(varDeclArray, input.getOtherVars());

            templateXLS = tl.getTemplateFile(input.getConstantParam_temporaryFolder(), input.getDocumentClassId(), conn, TemplatesLoader.TemplatesLoaderFiles.XLS_FILE);
            LoggingFacade.trace.info("got a template XLS from DB:" + templateXLS.getAbsolutePath());

            doFileTypeRelatedProcessing();

            try {
                templateXLS.delete();
                templateXML.delete();
            } catch (Exception e) {
                throw new MyXMLException("FromDB", "while deleting temporary templates files", "", e.getMessage());
            }
        } catch (MyException e) {
            if (templateXLS != null) {
                templateXLS.delete();
            }
            if (templateXML != null) {
                templateXML.delete();
            }
            if (res != null) {
                res.delete();
            }
            throw e;
        } finally {
            if (templateXLS != null) {
                templateXLS.delete();
            }
            if (templateXML != null) {
                templateXML.delete();
            }
            return res;
        }

    }

    protected abstract void doFileTypeRelatedProcessing() throws MyException;

    private void fillSingleFromDBQueryFromInputIfExists(
            VariableDeclaration[] varDecl,
            String singleFromDBQuery) {
        if (singleFromDBQuery != null
                && !singleFromDBQuery.equals("")) {
            for (VariableDeclaration vd : varDecl) {
                if (vd.isInIteration()) {
                    vd.setIterationRowSingleFromDBQuery(singleFromDBQuery);
                }
            }
        }
    }

    private void fillOtherVarsInVarDeclArrWithValuesFromInput(
            VariableDeclaration[] varDeclArray,
            ArrayList<Variable> inputZeroVars)
            throws MyXMLException {

        for (VariableDeclaration vd : varDeclArray) {
            if ((vd.getVarType().getDB_Relation().equals(VariableType_DBRelationTypes.SELECT) || (vd.getVarType().getDB_Relation().equals(VariableType_DBRelationTypes.NONE)))
                    && !vd.isInIteration()) {
                //find it in input
                for (Variable var : inputZeroVars) {
                    if (var.getName().equals(vd.getVarName())) {
                        vd.setValue(var.getValue());
                    }
                }
            }
        }

    }

    @Deprecated
    private String getXLS_FileName_From_NameTemplate(
            String nameTemplate,
            VariableDeclaration[] varDeclArr) throws MyException {

        //1. set variables in name
        return Util.filltemplateNamewithVariablesValues(nameTemplate, varDeclArr);
        //2. return :-)
    }
}
